<template>
  <div class="app-container">
    <br>
    <br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="采购单号" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="采购计划" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.plan }}
        </template>
      </el-table-column> -->
      <el-table-column label="采购类型" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      <el-table-column label="采购部门" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deptName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品类数量" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugTypeNum }}
        </template>
      </el-table-column>
      <el-table-column label="总数量" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugNum }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.godownStatus | statusColorFilter">{{ scope.row.godownStatus | statusNameFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" align="center" width="300" >
        <template slot-scope="scope">
          <el-button type="primary"  @click="getInfo(scope.row)" size="small">详情</el-button>
          <el-button type="success"  @click="update(scope.row)" size="small" v-if="scope.row.godownStatus != 2">入库</el-button>
          <!-- <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="->, total, prev, pager, next"
      :total="this.total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="clickCurPage"
      >
    </el-pagination>
  <el-dialog title="入库详情" :visible.sync="infoVisible" width="1500px">
    <h2>基本信息</h2>
    <el-form ref="info" :model="info" label-width="80px">
      <el-form-item label="采购单号">
          <el-input v-model="info.code" :disabled="true" />
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="采购类型">
              <el-input v-model="info.type" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="供货商">
            <el-select v-model="info.supplier" placeholder="请选择" style="width: 100%" :disabled="true" >
              <el-option
                v-for="item in suppliers"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="库房">
            <el-select v-model="info.applyDepository" placeholder="请选择" style="width: 100%" :disabled="true" >
              <el-option
                v-for="item in depositoryEnum"
                :key="item.id"
                :label="item.name + ' ' + ' (' + info.deptName + ')'"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="品类数量">
              <el-input v-model="info.drugTypeNum" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="总数量">
              <el-input v-model="info.drugNum" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <h3>采购药品</h3>
      <el-form-item label="药品" >
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <el-form-item v-for="(drug, drugIndex) in info.purchaseOrderDrugList" :key="drugIndex" style="border-bottom: 1px solid #E4E7ED;">
            <div v-for="(opt, optIndex) in drug.operationList" :key="optIndex">
              <div style="display: flex;flex-direction: row;width: 100%;padding: 5px;" v-for="(godown, godownIndex) in opt.godownDrugList" :key="godownIndex" >
                <div class="drug-name" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}" ><span>{{drug.drugName + ' ' + drug.form + ' ' + drug.drugSpecs}}</span></div>
                <div class="drugs-item" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}" >
                  <span class="drugs-item-title" style="width: 140px;">采购数量</span>
                  <el-input type="Number" min=0 class="drug-input" v-model="opt.num" :disabled="true">
                  </el-input>
                </div>
                <el-divider direction="vertical"></el-divider>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">批号</span>
                  <el-input class="drug-input" v-model="godown.batchCode" :disabled="true" ></el-input>
                </div>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">生产日期</span>
                  <el-date-picker v-model="godown.productTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 140px;margin-right: 10px;" :disabled="true" ></el-date-picker>
                </div>
                <div class="drugs-item" >
                  <span class="drugs-item-title" style="width: 140px;">保质期（月）</span>
                  <el-input class="drug-input" v-model="godown.qualityTime" :disabled="true" ></el-input>
                </div>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">有效期至</span>
                  <el-date-picker v-model="godown.expirationTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 140px;margin-right: 10px;" :disabled="true" ></el-date-picker>
                </div>
                <div class="drugs-item">
                  <span class="drugs-item-title" style="width: 140px;">{{'入库数量(' + drug.outerUnit + ')'}}</span>
                  <el-input type="Number" min=0 class="drug-input" v-model="godown.godownNum" :disabled="true" ></el-input>
                </div>
              </div>
            </div>
            
            
          </el-form-item>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog :title="dialogTitle" :visible.sync="formVisible" width="1500px" :close-on-click-modal="false" >
    <h2>基本信息</h2>
    <el-form ref="form" :model="form" label-width="80px" :rules="formRules">
      <el-form-item label="采购单号" v-if="form.code != '---'">
          <el-input v-model="form.code" :disabled="true" />
      </el-form-item>
      <el-row :gutter="10">
        <!-- <el-col :span=8>
          <el-form-item label="采购计划" prop="plan">
              <el-input v-model="form.plan" :disabled="true" />
          </el-form-item>
        </el-col> -->
        <el-col :span=8 >
          <el-form-item label="采购类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择" style="width: 100%" :disabled="true" >
              <el-option
                v-for="item in typeEnum"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="供货商">
            <el-select v-model="form.supplier" placeholder="请选择" style="width: 100%" :disabled="true" >
              <el-option
                v-for="item in suppliers"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="库房" prop="dept">
            <el-select v-model="form.applyDepository" placeholder="请选择" style="width: 100%" :disabled="true" >
              <el-option
                v-for="item in depositoryEnum"
                :key="item.id"
                :label="item.name + ' ' + ' (' + form.deptName + ')'"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="品类数量">
              <el-input v-model="form.drugTypeNum" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="总数量">
              <el-input v-model="form.drugNum" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <h3>采购药品</h3>
      <el-form-item label="药品">
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <el-form-item v-for="(drug, drugIndex) in form.purchaseOrderDrugList" :key="drugIndex" style="border-bottom: 1px solid #E4E7ED;" >
            <div v-for="(opt, optIndex) in drug.operationList" :key="optIndex">
              <div style="display: flex;flex-direction: row;width: 100%;padding: 5px;" v-for="(godown, godownIndex) in opt.godownDrugList" :key="godownIndex" >
                <div class="drug-name" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}" >{{drug.drugName + ' ' + drug.form + ' ' + drug.drugSpecs}}</div>
                <div class="drugs-item" :style="{'opacity': godownIndex===0?1:0, 'pointer-events': godownIndex!=0?'none':''}" >
                  <span class="drugs-item-title" style="width: 140px;">采购数量</span>
                  <el-input type="Number" min=0 class="drug-input" v-model="opt.num" :disabled="true" @input="inputDrugNum"></el-input>
                </div>
                <el-divider direction="vertical"></el-divider>
                <div class="drugs-item" >
                  <span class="drugs-item-title" style="width: 140px;">批号</span>
                  <el-input class="drug-input" v-model="godown.batchCode" :disabled="godown.id != undefined"></el-input>
                </div>
                <div class="drugs-item" >
                  <span class="drugs-item-title" style="width: 140px;">生产日期</span>
                  <el-date-picker v-model="godown.productTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 140px;margin-right: 10px;" :disabled="godown.id != undefined"></el-date-picker>
                </div>
                <div class="drugs-item" >
                  <span class="drugs-item-title" style="width: 140px;">保质期（月）</span>
                  <el-input class="drug-input" v-model="godown.qualityTime" :disabled="godown.id != undefined || godown.productTime === undefined " @input="inputQualityTime(godown)"></el-input>
                </div>
                <div class="drugs-item" >
                  <span class="drugs-item-title" style="width: 140px;">有效期至</span>
                  <el-date-picker v-model="godown.expirationTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 140px;margin-right: 10px;" :disabled="godown.id != undefined || godown.productTime === undefined" @input="inputExpirationTime(godown)" ></el-date-picker>
                </div>
                <div class="drugs-item" >
                  <span class="drugs-item-title" style="width: 140px;">{{'入库数量(' + drug.outerUnit + ')'}}</span>
                  <el-input type="Number" min=0 class="drug-input" v-model="godown.godownNum" :disabled="godown.id != undefined" @input="inputGodownNum(opt, godown)">
                  </el-input>
                </div>
                
                <div style="display: flex;flex-direction: column;justify-content: center;margin-right: 5px;" v-if="godownIndex===0" >
                  <el-button type="primary" circle style="width: 20px;height: 20px;align-items: center;display: flex;justify-content: center;" @click="addDrugGodown(opt)">+</el-button>
                </div>
                <div style="display: flex;flex-direction: column;justify-content: center;margin-right: 5px;" v-if="godownIndex!=0">
                  <el-button type="danger" circle style="width: 20px;height: 20px;align-items: center;display: flex;justify-content: center;" @click="delDrugGodown(drug, drugIndex, godownIndex)" :disabled="godown.godownNum != undefined">-</el-button>
                </div>
              </div>
            </div>
            
          </el-form-item>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirm">确 定</el-button>
        <div style="width:200px;display: inline-block;"> </div>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script>
import { getList, getInfo, addorupdate, del, input } from '@/api/purchaseOrder'
import { getInfo as godownInfo} from '@/api/godown'
import { getList as getSupplierList } from '@/api/supplier'
import { getList as getStoreList } from '@/api/store'
import { dateToString, stringToDate } from '@/utils/dateUtil'

export default {
  filters: {
    statusColorFilter(status) {
      const statusMap = ['info', 'success', 'primary']
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = ['未入库', '部分入库', '全部入库']
      return statusMap[status]
    }
  },
  data() {
    // const validatePlan = (rule, value, callback) => {
    //   if (!value) callback(new Error('请填写计划名称')) 
    //   else callback()
    // }
    const validateType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型'))
      else callback()
    }
    const validateDept = (rule, value, callback) => {
      if (!value) callback(new Error('请选择部门'))
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 20,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      dialogTitle: '',
      info: {},
      form: {},
      purchaseOrderDrugList: [],
      typeEnum: ["集中", "临时"],
      depositoryEnum: [],
      suppliers: [],
      query: {},
      tagEnum: [{id: 1, name: '热销'},{id: 2, name: '促销'}],
      dugTypeTreeList: [],
      formRules: {
        // plan: [{ required: true, trigger: 'blur', validator: validatePlan }],
        type: [{ required: true, trigger: 'blur', validator: validateType }],
        dept: [{ required: true, trigger: 'blur', validator: validateDept }],
      },
      searchValue: '',
      loginDeptId: undefined,
    }
    
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      var loginInfo = this.$store.getters.userInfo.loginInfo
      this.loginDeptId = loginInfo.loginDept.deptId
      const reqBody = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          deptId: this.loginDeptId,
          status: 2,
      }
      getList(reqBody).then(response => {
        console.log(response)
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
        
      })
      getStoreList().then(deptRes=> {
        this.depositoryEnum = deptRes.data
      })
      getSupplierList().then(supplierRes => {
        console.log(supplierRes)
        this.suppliers = supplierRes.data
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    add() {
      this.reset()
      this.dialogTitle = '申请采购单'
      this.form.code = '---'
      this.form.drugTypeNum = 0
      this.form.drugNum = 0
      this.form.status = 0
      this.$set(this.form, 'purchaseOrderDrugList', [])
      this.formVisible = true
    },
    getInfo(row) {
      godownInfo({id: row.id,deptId: this.loginDeptId}).then(infoRes=>{
        console.log(infoRes)
        this.info = infoRes.data
        this.info.purchaseOrderDrugList.forEach(drugItem=>{
          drugItem.operationList.forEach(operationItem=>{
            operationItem.godownDrugList.forEach(godownItem=> {
              this.inputExpirationTime(godownItem)
            })
            if(operationItem.godownDrugList.length === 0) {
              operationItem.godownDrugList.push({})
            }
          })
        })
        this.infoVisible = true
      })
    },
    update(row) {
      this.reset()
      this.dialogTitle = '入库'
      godownInfo({id: row.id,deptId: this.loginDeptId}).then(infoRes=>{
        console.log("infoRes", infoRes)
        this.form = JSON.parse(JSON.stringify(infoRes.data))
        this.form.purchaseOrderDrugList.forEach(drugItem=>{
          drugItem.operationList.forEach(operationItem=>{
            operationItem.godownDrugList.forEach(godownItem=> {
              this.inputExpirationTime(godownItem)
            })
            if(operationItem.godownDrugList.length === 0) {
              operationItem.godownDrugList.push({})
            }
          })
        })
        this.formVisible = true
      })
    },
    deleteInfo(scope) {
      this.$confirm('确定删除该职务?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.checkGoDownNum()
          this.listLoading = true
          var requreParam = this.buildRequreParam(this.form)
          console.log("requreParam", requreParam)
          input(requreParam).then(res=>{
            console.log(res)
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.formVisible = false
            this.listLoading = false
            this.$tab.refreshPage({path: '/store/input', name: "Input"});
          }).catch(err=>{
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    buildRequreParam(form) {
      var goDownDrugBOList = []
      for (const drug of form.purchaseOrderDrugList) {
        for (const opt of drug.operationList) {
          for (const godown of opt.godownDrugList) {
            if(godown.id === undefined) {
              goDownDrugBOList.push({
                drugCode: drug.drugCode,
                batchCode: godown.batchCode,
                operationId: opt.id,
                num: Number(godown.godownNum),
                productTime: godown.productTime,
                expiration: godown.expirationTime,
              })
            }
          }
        }
      }
      var requreParam = {
        purchaseOrderId: form.id,
        drugDepositoryId: form.applyDepository,
        supplier: form.supplier,
        source: "外采",
        goDownDrugBOList: goDownDrugBOList,
      }
      return requreParam;
    },
    cancel() {
      this.infoVisible = false
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    addDrugGodown(opt) {
      // opt.godownDrugList;
      // var godownItem = JSON.parse(JSON.stringify(opt.godownDrugList[0]))
      // godownItem.productTime = undefined
      // godownItem.expirationTime = undefined
      var sumGodownNum = 0
      if(opt.godownDrugList) sumGodownNum = opt.godownDrugList.filter(drug => drug.id != undefined).reduce((sum, obj) => Number(sum) + Number(obj.godownNum), 0);
      if(Number(sumGodownNum) >= opt.num) {
        this.$message.error("该药品已完成入库")
        return;
      }
      opt.godownDrugList.push({})
    },
    delDrugGodown(drug, drugIndex, godownIndex) {
      if(godownIndex === 0) {
        this.form.purchaseOrderDrugList.splice(drugIndex, 1)
        this.form.drugTypeNum--
      } else {
        drug.godownDrugList.splice(godownIndex, 1)
      }
      this.form.drugNum = this.form.purchaseOrderDrugList.reduce((sum, obj) => Number(sum) + Number(obj.num), 0);
    },
    inputDrugNum() {
      this.form.drugNum = this.form.purchaseOrderDrugList.reduce((sum, obj) => Number(sum) + Number(obj.num), 0);
    },
    inputQualityTime(godown) {
      var expirationTime = stringToDate(godown.productTime)
      var year = expirationTime.getFullYear();
      var month = expirationTime.getMonth() + Number(godown.qualityTime);
      expirationTime.setFullYear(year + Math.floor(month / 12)); // 设置年份
      expirationTime.setMonth(month % 12); // 设置月份
      this.$set(godown, 'expirationTime', expirationTime)
    },
    inputExpirationTime(godown) {
      var productTime = stringToDate(godown.productTime)
      var productYear = productTime.getFullYear();
      var productMonth = productTime.getMonth();
      var expirationTime = stringToDate(godown.expirationTime)
      var expirationYear = expirationTime.getFullYear();
      var expirationMonth = expirationTime.getMonth();
      this.$set(godown, 'qualityTime', expirationMonth - productMonth + (expirationYear - productYear)*12)
    },
    inputGodownNum(opt, godown) {
      var sumGodownNum = 0
      if(opt.godownDrugList) sumGodownNum = opt.godownDrugList.filter(drug => drug.id != undefined).reduce((sum, obj) => Number(sum) + Number(obj.godownNum), 0);
      if(Number(sumGodownNum) + Number(godown.godownNum) > opt.num) {
        this.$message.error('超过采购数量，已自动计算')
        this.$set(godown, 'godownNum', opt.num - sumGodownNum)
      }
    },
    checkGoDownNum() {
      this.form.purchaseOrderDrugList.forEach(purchaseOrder=>{
        purchaseOrder.operationList.forEach(optItem=> {
          optItem.godownDrugList.forEach(godownDrug=>{
            if(godownDrug.batchCode == undefined || godownDrug.batchCode == '') {
              this.$message.error('请填写批号')
              throw new Error('请填写批号')
            } else if(godownDrug.productTime == undefined) {
              this.$message.error('请填写生产日期')
              throw new Error('请填写生产日期')
            } else if(godownDrug.expirationTime == undefined) {
              this.$message.error('请填写过期时间')
              throw new Error('请填写过期时间')
            } else if(godownDrug.godownNum == undefined || Number(godownDrug.godownNum) <= 0) {
              this.$message.error('请填写入库数量')
              throw new Error('请填写入库数量')
            }
          })
        })
      })
    },
  }
}

</script>

<style>
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .drug-input {
    width: 100%;
    display: inline-block;
    margin-right: 10px;
  }
  .drugs-item-title {
    line-height: 20px;
    text-align: center;
    background-color: #E4E7ED;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  .drugs-item {
    width: 140px;
    display: flex;
    flex-direction: column;
    margin-right: 10px;
  }
  .drug-name {
    width: 300px;
    margin-right: 20px;
    font-size: 15px;
    height: 58px;
    line-height: 58px;
  }
</style>